package cn.openea.perpartner.auth.controller;


import cn.hutool.core.util.IdUtil;
import cn.openea.perpartner.common.auth.config.AuthConfig;
import cn.openea.perpartner.common.auth.entity.LoginBody;
import cn.openea.perpartner.common.auth.login.LoginService;
import cn.openea.perpartner.common.auth.util.SessionUtil;
import cn.openea.perpartner.common.core.constant.Constants;
import cn.openea.perpartner.common.core.manager.AsyncManager;
import cn.openea.perpartner.common.core.utils.MessageUtils;
import cn.openea.perpartner.common.core.web.domain.AjaxResult;
import cn.openea.perpartner.common.log.factory.AsyncFactory;
import cn.openea.perpartner.system.entity.SysUser;
import cn.openea.perpartner.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Administrator
 */
@Controller
public class WebController {
    @Autowired
    private ISysUserService userService;
    @Autowired
    private LoginService loginService;
    /**
     *访问首页时 查看是否登录
     */
    @RequestMapping("/")
    public String index(Model model, HttpServletRequest request, HttpServletResponse response) {
        // 校验是否登录
        LoginBody user = loginService.loginCheck(request, response);
        if (user == null) {
            return "redirect:/login";
        } else {
            model.addAttribute("loginUser", user);
            return "index";
        }
    }

    /**
     *访问修改密码时 查看是否登录
     */
    @RequestMapping("/editpass")
    public String editpass(Model model, HttpServletRequest request, HttpServletResponse response) {
        // 校验是否登录
        LoginBody user = loginService.loginCheck(request, response);
        if (user == null) {
            return "redirect:/login";
        } else {
            String redirectUrl = request.getParameter(AuthConfig.REDIRECT_URL);
            model.addAttribute("redirectUrl", redirectUrl);
            model.addAttribute("loginUser", user);
            return "editpass";
        }
    }

    /**
     * 访问登录页面 查看是否登录
     */
    @RequestMapping("/login")
    public String login(Model model, HttpServletRequest request, HttpServletResponse response){
        //校验是否登录
        LoginBody user = loginService.loginCheck(request, response);
        if (user != null) {
            // success redirect
            String redirectUrl = request.getParameter(AuthConfig.REDIRECT_URL);
            if (redirectUrl!=null && redirectUrl.trim().length()>0) {
                String sessionId = loginService.getSessionIdByCookie(request);
                String redirectUrlFinal = redirectUrl + "?" + AuthConfig.SSO_SESSIONID + "=" + sessionId;
                return "redirect:" + redirectUrlFinal;
            } else {
                return "redirect:/";
            }
        }
        model.addAttribute("errorMsg", request.getParameter("errorMsg"));
        model.addAttribute(AuthConfig.REDIRECT_URL, request.getParameter(AuthConfig.REDIRECT_URL));
        return "login";
    }
    /**
     *  doLogin 登录请求
     *  前台login表单传送
     */
    @RequestMapping("/doLogin")
    public String login(HttpServletRequest request,
                        HttpServletResponse response,
                        RedirectAttributes redirectAttributes,
                        String userId, String password, String ifRem){
        //查询数据库 以确定用户是否存在
        AjaxResult ajaxResult = userService.checkUser(userId, password);
        SysUser user = (SysUser) ajaxResult.get(AjaxResult.DATA_TAG);
        if (user!= null){
            boolean isRem = "on".equals(ifRem);
            LoginBody loginBody = new LoginBody();
            loginBody.setUserid(String.valueOf(user.getUserid()));
            loginBody.setUsername(user.getNickname());
            loginBody.setVersion(IdUtil.fastSimpleUUID());
            loginBody.setExpireMinute(loginService.getRedisExpireMinute());
            loginBody.setExpireFreshTime(System.currentTimeMillis());
            // 生成sessionId
            String sessionId = SessionUtil.makeSessionId(loginBody);
            //登录,存储storeKey
            loginService.login(response, sessionId, loginBody, isRem);
            //登录记录
            AsyncManager.me().execute(AsyncFactory.recordLoginInfo(userId, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
            //返回重定向url
            String redirectUrl = request.getParameter(AuthConfig.REDIRECT_URL);
            if (redirectUrl!=null && redirectUrl.trim().length()>0) {
                String redirectUrlFinal = redirectUrl + "?" + AuthConfig.SSO_SESSIONID + "=" + sessionId;
                return "redirect:" + redirectUrlFinal;
            }
        }
        redirectAttributes.addAttribute("errorMsg", ajaxResult.get(AjaxResult.MSG_TAG));
        redirectAttributes.addAttribute(AuthConfig.REDIRECT_URL, request.getParameter(AuthConfig.REDIRECT_URL));
        return "redirect:/login";
    }
    @RequestMapping("/logout")
    public String logout(HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
        loginService.logout(request, response);
        redirectAttributes.addAttribute(AuthConfig.REDIRECT_URL, request.getHeader("referer"));
        return "redirect:/login";
    }
}
